package org.isouland.cpwx.api.core.util;

import org.isouland.cpwx.api.base.WxAccessTokenAPI;
import org.isouland.cpwx.api.common.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tencent.common.Configure;

public class SingleAccessToken {
	private static Logger log = LoggerFactory.getLogger(SingleAccessToken.class);  

    private AccessToken accessToken;
    private static SingleAccessToken singleAccessToken;
    /**
     * 私有构造函数
     */
    private SingleAccessToken(){

        accessToken = WxAccessTokenAPI.getAccessToken(Configure.getAppid(), Configure.getAppsecret());
        log.info("获取access_token成功，有效时长{}秒 token:{}", accessToken.getExpiresIn(), accessToken.getAccesstoken());  
        initThread();
    }
    /**
     * 获取SingleAccessToken对象
     * @return
     */
    public static SingleAccessToken getInstance(){
        if(singleAccessToken==null){
            singleAccessToken=new SingleAccessToken();
        }
        return singleAccessToken;
    }
    
    /**
     * 清空singleAccessToken
     */
    public static void clearInstance(){
    	singleAccessToken=null;
    }

    public AccessToken getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(AccessToken accessToken) {
        this.accessToken = accessToken;
    }
    /**
     * 开启线程，设置SingleAccessToken为空
     */
    private void initThread(){
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                   //睡眠7000秒
                    Thread.sleep(7000*1000);    
                    singleAccessToken=null;

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();
    }

}